package com.benefm.multipar.pad.dashboard;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.benefm.multipar.pad.AppConfig;
import com.benefm.multipar.pad.R;
import com.benefm.multipar.pad.ble.BLEManager;
import com.benefm.multipar.pad.databinding.ActivityOnlineDeviceBinding;
import com.benefm.multipar.pad.event.EventAction;
import com.benefm.multipar.pad.event.MsgEvent;
import com.benefm.multipar.pad.util.ACache;
import com.benefm.multipar.pad.view.LoadingDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.data.BleScanState;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class BleDeviceListActivity extends AppCompatActivity implements OnItemClickListener {

    private ActivityOnlineDeviceBinding binding;

    private List<BleDevice> deviceList = new ArrayList<>();

    private BleDeviceListAdapter deviceAdapter;

    private LoadingDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_online_device);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

        dialog = new LoadingDialog(this);

        EventBus.getDefault().register(this);

        deviceAdapter = new BleDeviceListAdapter(deviceList);
        binding.recyclerView.setAdapter(deviceAdapter);
        deviceAdapter.setOnItemClickListener(this);

        checkPermission();

        binding.refresh.setOnClickListener(v -> {
            if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING)
                return;
            checkPermission();
        });

    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.BLUETOOTH,
                            Manifest.permission.BLUETOOTH_SCAN,
                            Manifest.permission.BLUETOOTH_CONNECT}, 11);
        } else {
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH}, 11);
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent event) {
        if (EventAction.DEVICE_FOUND == event.getAction()) {
            BleDevice bleDevice = (BleDevice) event.getT();
            filterOriginal(bleDevice);
        } else if (EventAction.DEVICE_CONNECTED == event.getAction()) {
            dialog.dismiss();
            Toast.makeText(this, "连接成功", Toast.LENGTH_LONG).show();
//            startActivity(new Intent(this, EcgWaveBleActivity.class));
            startActivity(new Intent(this, DashboardActivity.class));
        } else if (EventAction.DEVICE_CONNECT_FAIL == event.getAction()) {
            dialog.dismiss();
        } else if (EventAction.SCAN_START == event.getAction()) {
            binding.refresh.setVisibility(View.GONE);
            binding.progressBar.setVisibility(View.VISIBLE);
        } else if (EventAction.SCAN_FINISH == event.getAction()) {
            binding.refresh.setVisibility(View.VISIBLE);
            binding.progressBar.setVisibility(View.GONE);
            List<BleDevice> resultList = (List<BleDevice>) event.getT();
            syncLists(resultList);
        }

    }

    private void filterOriginal(BleDevice bleDevice) {
        boolean isAdd = true;
        //后台会进行多次扫描 过滤重复的设备
        for (BleDevice device : deviceList) {
            if (bleDevice.getMac().equals(device.getMac())) {
                isAdd = false;
                break;
            }
        }
        if (isAdd) {
            deviceList.add(bleDevice);
            deviceAdapter.notifyDataSetChanged();
        }
    }

    private void syncLists(List<BleDevice> resultList) {
        // 创建临时列表避免并发修改异常
        List<BleDevice> toRemove = new ArrayList<>();
        for (BleDevice item : deviceList) {
            if (!resultList.contains(item)) {
                toRemove.add(item);
            }
        }
        deviceList.removeAll(toRemove);
        // 添加新元素
        for (BleDevice item : resultList) {
            if (!deviceList.contains(item)) {
                deviceList.add(item);
            }
        }
        deviceAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

        dialog.showDialog(false);

        final BleDevice bleDevice = (BleDevice) adapter.getItem(position);

        new Handler(Looper.getMainLooper()).postDelayed(() -> BLEManager.getInstance().connectDevice(bleDevice), 500);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 11) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED
                        && grantResults[2] == PackageManager.PERMISSION_GRANTED && grantResults[3] == PackageManager.PERMISSION_GRANTED) {
                    BLEManager.getInstance().scanDevice();
                }
            } else {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    BLEManager.getInstance().scanDevice();
                }
            }

        }

    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("此操作将会退出当前界面，请确认！")
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    BleDeviceListActivity.this.finish();
                })
                .create()
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING) {
            BleManager.getInstance().cancelScan();
        }
        EventBus.getDefault().unregister(this);
    }
}
